package conf

import (
	"flag"
	"fmt"
	"time"

	"github.com/GoAdminGroup/go-admin/modules/config"
	"github.com/nsqio/go-nsq"
	"github.com/spf13/viper"
	"gorm.io/gorm/schema"

	"mini-admin/pkg/orm"
)

var (
	Conf       = &Config{}
	configFile string
)

// Config 配置
type Config struct {
	ORM *orm.Config `mapstructure:"orm"`
	NSQ *nsq.Config `mapstructure:"nsq"`

	HTTP           *HTTP  `mapstructure:"http"`
	NSQAddr        string `mapstructure:"nsq_address"`
	OpenAddress    string `mapstructure:"open_address"`
	WechatAppID    string `mapstructure:"wechat_app_id"`
	AlipayAppID    string `mapstructure:"alipay_app_id"`
	BytedanceAppID string `mapstructure:"bytedance_app_id"`

	Admin config.Config
}

// HTTP 服务配置
type HTTP struct {
	Port string `mapstructure:"port"`
}

// NewConfig new config
func NewConfig() *Config {
	NSQ := nsq.NewConfig()
	NSQ.MaxInFlight = 2
	return &Config{
		ORM: &orm.Config{
			DSN:         "host=127.0.0.1 port=5432 user=cluas dbname=mini sslmode=disable",
			Active:      5,
			Idle:        5,
			IdleTimeout: time.Hour * 4,
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
			},
		},
		HTTP: &HTTP{Port: ":9033"},
		NSQ:  NSQ,
	}
}

func init() {
	flag.StringVar(&configFile, "c", "cmd/admin/config-example.toml", "path of x config file.")
}

// Init is func to initial log config
func Init() (err error) {
	Conf = NewConfig()
	viper.SetConfigFile(configFile)

	if err = viper.ReadInConfig(); err != nil {
		return err
	}

	if err = viper.Unmarshal(&Conf); err != nil {
		panic(fmt.Errorf("Unable to decode into struct：%s ", err))
	}

	return nil
}
